package bgw

import (
	"context"
	"net/http"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/logic/pay"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/consts"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bgw"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PaymentNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// bgw代收回调通知
func NewPaymentNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PaymentNotifyLogic {
	return &PaymentNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PaymentNotifyLogic) PaymentNotify(req *types.BgwPaymentNotifyReq, r *http.Request) (resp *types.BgwPaymentNotifyResp, err error) {
	// 回调信息转为 json 字符串
	b, _ := sonic.MarshalString(req)
	h, _ := sonic.MarshalString(r.Header)
	logc.Info(l.ctx, b, h)
	// 获取 bgw 配置信息
	conf, err := l.svcCtx.AssetsRpc.PayRecharge.RechargeChannelListByCode(l.ctx, &rpc.RechargeChannelByCodeRequest{Code: consts.BgwCode})
	if err != nil {
		return nil, err
	}
	// 验签
	wsse, err := bgw.ParseXWSSE(r.Header.Get("X-WSSE"))
	if err != nil {
		return nil, err
	}
	pwdDigest := bgw.GeneratePasswordDigest(wsse["Nonce"], wsse["Created"], conf.SecretKey)
	if pwdDigest != wsse["PasswordDigest"] {
		logc.Error(l.ctx, pwdDigest, h)
		return nil, xerrors.ErrPwdDigestVerifyFailed
	}
	bodySign, err := bgw.ParseBodySign(r.Header.Get("Body-Sign"))
	if err != nil {
		return nil, err
	}
	sign := bgw.GenerateBodySign(b, conf.AppCode, conf.SecretKey, r.Header.Get("Request-Id"))
	if sign != bodySign["signature"] {
		logc.Error(l.ctx, sign, h)
		return nil, xerrors.ErrSignVerifyFailed
	}

	// 根据订单状态处理业务逻辑
	switch req.Status {
	case 2:
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeSuccess(l.ctx, &rpc.NotifyOKRequest{OrderNo: req.OuterNo, ReturnJson: b})
		if err != nil {
			logc.Error(l.ctx, err, b, h)
			return
		}
		pay.NewHandleOrderLogic(l.ctx, l.svcCtx).AddNotifitionMessage(&pay.NotifyMessageInfo{OrderNo: req.OuterNo})
		resp = &types.BgwPaymentNotifyResp{Ok: true}
	case 3, 4:
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeFail(l.ctx, &rpc.NotifyFailRequest{OrderNo: req.OuterNo, ReturnJson: b})
		if err != nil {
			logc.Error(l.ctx, err, b, h)
			return
		}
		resp = &types.BgwPaymentNotifyResp{Ok: true}
	}
	return
}
